<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者:奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\user\controller;
use think\Db;
class Guarantee extends Base
{
     public function initialize()
    {
       parent::initialize();
       $this->isLogin();
       //检查是否为支付订单，超过10分钟关闭
       $map = [];
       $map[]  = ['order_status','IN',[0,1]];
       $map[]  = ['pay_status','=',0];
       $map[]  = ['shipping_status','=',0];
       $order = model('guarantee')->where([$map])->where('seller_uid|buyer_uid','=',session('uid'))->select()->toArray();
         foreach($order as $k=>$v){
             
                       if(time() - $v['create_time'] > 10*60){
                         $data =[];
                         $where['id'] = $v['id'];
                         $data['order_status'] = 2;  //超过10分钟自动订单取消
                         $data['close_time'] = $v['create_time']+10*60; //10分钟后
                         model('guarantee')->where($where)->data($data)->update();
                       }
               }
               
    }
//所有交易
	public function index(){
       

       return $this->fetch();
	}
 

  
  public function info()
  {

      
          $param = $this->request->param();


          if($this->request->isPost()){

         
         $keywords  = !empty($param['keywords'])?$param['keywords']:''; //当前页
          $statusType =  isset($param['status'])?intval($param['status']):'all'; //请求状态

         //状态筛选
           switch($statusType)
           {
      
            case 1:
               //待审核
              
               $where[] = ['status','=',0];
            break;
            case 2:
            // 已审核
              
                $where[] = ['status','=',1];
            break;
            case 3:
            // 交易中
             
                $where[] = ['status','=',2];
            break; 
            case 4:
            // 交易完成
               
                $where[] = ['status','=',3];
            break; 
            case 5:
            // 审核失败
             
               $where[] = ['status','=',-1];
            break;

           }
       if($keywords){
           $where[]= ['title','like',"%$keywords%"];
        }
  
         
     }
        $where[] = ['uid','=',session('uid')];
        $order ="create_time desc";
        $count  = Db::name('guaranteeInfo')->where($where)->whereOr($where1)->count();
        $lists = Db::name('guaranteeInfo')->where($where)->whereOr($where1)->order($order)->paginate(10,false,['query'=>$data]);
   
         $list  = $lists->toArray()['data'];
      // 获取分页显示
      $page = $lists->render();
      $this->assign('page',$page);
      $this->assign('list',$list);
      return $this->fetch();
   
  }
//信息编辑
public function infoEdit()
{
  $param = $this->request->param();

   if($this->request->isAjax()){
     
      $id           = $param['id'];
      if(empty($id)){
        $this->error('参数不存在');
      }
      $where['id']  = intval($id);
      $where['uid']  = session('uid');
      $where['status']  = 0;
      $data['title'] = $param['title'];
      $data['price'] = $param['price'];
      $data['content'] = $param['content'];
      model('guaranteeInfo')->editData($data,$where);
       return success_json('修改成功');
   }else{
     if(empty($param['id'])){
         $this->error('参数错误');
     }
     $where['id'] = $param['id'];
     $where['uid'] = session('uid');
     $info = model('guaranteeInfo')->infoData($where);
     $this->assign('info',$info);
     return $this->fetch();
   }
}

//信息删除
public function infoDel()
{
   if($this->request->isAjax()){
      $param = $this->request->param();
      $id           = $param['id'];
      if(empty($id)){
        $this->error('参数不存在');
      }
      $where['id']  = intval($id);
      $where['uid']  = session('uid');
      model('guaranteeInfo')->delData($where);
       return success_json('删除成功');
   }
}
// 买家
 public function buyer()
 {
          $param = $this->request->param();
          $keywords  = !empty($param['keywords'])?$param['keywords']:''; 
          $status  = !empty($param['status'])?intval($param['status']):''; 
         

          $data['keywords'] = $keywords;
          if($keywords){
             $where[]= ['title','like',"%$keywords%"];
          }


  //状态筛选
           switch($status)
           {
            case '2':
            //等待卖家确认
              $where[] = ['pay_status','=',0];    //0 未确认  1  确认  2 取消 
              $where[] = ['order_status','=',0];  // 0未付款  1已付款 
              $where[] = ['shipping_status','=',0]; //0 未发货 1已发货 2已收货
            break;
            case '3':
            // 等待买家付款
              $where[] = ['order_status','=',1];    //0 未确认  1  确认  2 取消  
              $where[] = ['pay_status','=',0];      // 0未付款  1已付款 
              $where[] = ['shipping_status','=',0]; //0 未发货 1已发货 2已收货
            break;
            case '4':
            //等待卖家发货
              $where[] = ['order_status','=',1];     //0 未确认  1  确认  2 取消  
              $where[] = ['pay_status','=',1];       // 0未付款  1已付款 
              $where[] = ['shipping_status','=',0];  //0 未发货 1已发货 2已收货
            break; 
            case '5':
            // 等待买家确认
             $where[] = ['order_status','=',1];     //0 未确认  1  确认  2 取消  
             $where[] = ['pay_status','=',1];       // 0未付款  1已付款 
             $where[] = ['shipping_status','=',1];  //0 未发货 1已发货 2已收货
            break; 
            case '6':
            // 买家已确认，交易成功
             $where[] = ['order_status','=',1];     //0 未确认  1  确认  2 取消  
             $where[] = ['pay_status','=',1];       // 0未付款  1已付款 
             $where[] = ['shipping_status','=',2];  //0 未发货 1已发货 2已收货
            break;
             case '7':
            // 订单关闭
             $where[] = ['order_status','=',2];    //0 未确认  1  确认  2 取消  
             $where[] = ['pay_status','=',0];      // 0未付款  1已付款 
             $where[] = ['shipping_status','=',0];  //0 未发货 1已发货 2已收货
            break;
   
          }
         $where1 ="buyer = '".session('username')."'";
         $order ="create_time desc";
        $count  = Db::name('guarantee')->where($where)->where($where1)->count();
        $lists =  Db::name('guarantee')->where($where)->where($where1)->order($order)->paginate(10,false,['query'=>$data]);
         
        $list  = $lists->toArray()['data'];
         // 获取分页显示
        $page = $lists->render();
          // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch('order_list');

 }
// //卖家
 public function seller()
 {

       $param = $this->request->param();
          $keywords  = !empty($param['keywords'])?$param['keywords']:''; 
          $status  = !empty($param['status'])?intval($param['status']):''; 
    

          $data['keywords'] = $keywords;
          if($keywords){
             $where[]= ['title','like',"%$keywords%"];
          }
  //状态筛选
           switch($status)
           {
            case '2':
            //等待卖家确认
              $where[] = ['pay_status','=',0];    //0 未确认  1  确认  2 取消 
              $where[] = ['order_status','=',0];  // 0未付款  1已付款 
              $where[] = ['shipping_status','=',0]; //0 未发货 1已发货 2已收货
            break;
            case '3':
            // 等待买家付款
              $where[] = ['order_status','=',1];    //0 未确认  1  确认  2 取消  
              $where[] = ['pay_status','=',0];      // 0未付款  1已付款 
              $where[] = ['shipping_status','=',0]; //0 未发货 1已发货 2已收货
            break;
            case '4':
            //等待卖家发货
              $where[] = ['order_status','=',1];     //0 未确认  1  确认  2 取消  
              $where[] = ['pay_status','=',1];       // 0未付款  1已付款 
              $where[] = ['shipping_status','=',0];  //0 未发货 1已发货 2已收货
            break; 
            case '5':
            // 等待买家确认
             $where[] = ['order_status','=',1];     //0 未确认  1  确认  2 取消  
             $where[] = ['pay_status','=',1];       // 0未付款  1已付款 
             $where[] = ['shipping_status','=',1];  //0 未发货 1已发货 2已收货
            break; 
            case '6':
            // 买家已确认，交易成功
             $where[] = ['order_status','=',1];     //0 未确认  1  确认  2 取消  
             $where[] = ['pay_status','=',1];       // 0未付款  1已付款 
             $where[] = ['shipping_status','=',2];  //0 未发货 1已发货 2已收货
            break;
             case '7':
            // 订单关闭
             $where[] = ['order_status','=',2];    //0 未确认  1  确认  2 取消  
             $where[] = ['pay_status','=',0];      // 0未付款  1已付款 
             $where[] = ['shipping_status','=',0];  //0 未发货 1已发货 2已收货
            break;
   
          }
         $where1 ="seller = '".session('username')."'";
         $order ="create_time desc";
        $count  = Db::name('guarantee')->where($where)->where($where1)->count();
        $lists =  Db::name('guarantee')->where($where)->where($where1)->order($order)->paginate(10,false,['query'=>$data]);
         
        $list  = $lists->toArray()['data'];
         // 获取分页显示
        $page = $lists->render();
          // 模板变量赋值
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch('order_list');


 }
//更新订单状态

  public  function updateOrderStatus()
  {
    $param = $this->request->param();
    if(!$this->request->isAjax()){
      return error_json('请求错误');
    }
    $status = intval($param['status']);
   if(empty($status)){
       return error_json('订单不存在');
    }
    $where['id'] = intval($param['id']);

    $order = model('guarantee')->infoData($where);

    //状态筛选
           switch($status){
            case 1:
            // 卖家操作-确认订单状态
            if($order['order_status'] == 0 &&  $order['pay_status'] ==0 && $orde['shipping_status'] ==0){

              if($order['seller_uid'] = session('uid')){
                //给买家发送提醒  
                       $msg_data['title'] = '订单接受提醒';
                       $url = url('trade/order',['id'=>$order['id']]);
                       $content = "尊敬的 ".$order["buyer"].":<br>";
                       $content .= $order['seller'].'确认了您发起的交易:【<a href="'.$url.'">'.$order['title'].'</a>】,请尽快完成付款操作！<br>';
                   
                       $msg_data['content'] = $content;
                       $msg_data['to_uid'] = $order['buyer_uid'];
                       $msg_data['create_time'] = time();
                       model('message')->addData($msg_data);


                        $data['order_status'] = 1; //0 未确认  1  确认  2 取消  
                        $data['pay_status']   = 0;    // 0未付款  1已付款 
                        $data['shipping_status'] = 0;  //0 未发货 1已发货 2已收货
                        $data['confirm_time'] = time();  //卖家确认时间
                        $msg = '已同意请求';                      
                       model('guarantee')->editData($data,$where);
                       return success_json($msg);
              }
            }
            break;
            case 2:
            //买家操作 - 买家支付
           if($order['order_status'] == 1 &&  $order['pay_status'] ==0 && $orde['shipping_status'] ==0){

               if($order['buyer_uid'] = session('uid')){
                    if($this->user['money']  < $order['buyer_pay']){
                         return error_json('余额不足，请充值');
                     }
                  
                      model('user')->where(['uid'=>session('uid')])->setDec('money',$order['buyer_pay']);
                      $userinfo = model('user')->infoData("uid = ".session('uid'));

                      //添加流水记录
                      $data2['uid']       = session('uid');
                      $data2['username']  = session('username');
                      $data2['bankname']  = '余额支付';
                      $data2['amount']    = -$order['buyer_pay']; //买家支付
                      $data2['balance']   = $userinfo['money'];
                      $data2['remark']    = '订单支付，订单号：'.$order['id'];
                      $data2['create_time']   = time();
                      model('financeRecord')->addData($data2);

                      $data['order_status']    = 1;   // 0 未确认  1  确认  2 取消  
                      $data['pay_status']      = 1;    // 0未付款  1已付款 
                      $data['shipping_status'] = 0;    //0 未发货 1已发货 2已收货
                      $data['pay_time']   = time(); //买家支付时间
                      $msg = '恭喜您，支付成功';

                      model('guarantee')->editData($data,$where);

                      // 判断交易信息是否存在，存在则更新交易信息状态
                      if(!empty($order['info_id'])){
                        model('guarantee_info')->editData(['status'=>2],['id'=>$order['info_id']]);
                      }


                   //更新用户成交笔数
                    $buy_success_where[] = ['uid','=',session('uid')];
                    model('user')->where($buy_success_where)->setInc('buy_num',1);
        
                    $sell_success_where[] = ['uid','=',$order['seller_uid']];
                    model('user')->where($sell_success_where)->setInc('sell_num',1);


                  //给卖家发送通知提醒
                    $msg_data['title'] = '买家付款提醒';
                    $url = url('trade/order',['id'=>$order['id']]);
                    $msg_data['content'] = '交易订单【<a href="'.$url.'">'.$order['title'].'</a>】，买家 '.$order['buyer'].' 已付款，请尽快工作！';
                    $msg_data['to_uid'] = $order['seller_uid'];
                    $msg_data['create_time'] = time();
                    $msg_data['type'] = 0; //系统通知
                    model('message')->addData($msg_data);
                    return success_json($msg);
               }
             
            }else{
              return error_json('您已经付款，请勿重复操作！');
            }
            break; 
            case 3:
            // 卖家操作 - 卖家发货
            if($order['order_status'] == 1 &&  $order['pay_status'] ==1 && $orde['shipping_status'] ==0){
              
          
              if($order['seller_uid'] = session('uid')){
                //卖家
                       $msg_data['title'] = '订单交易提醒';
                       $msg_data['content'] = $msg;
                       $msg_data['to_uid'] = $order['buyer_uid'];
                        model('message')->addData($msg_data);

                      $data['order_status'] = 1; //0 未确认  1  确认  2 取消  
                      $data['pay_status'] = 1;    // 0未付款  1已付款 
                      $data['shipping_status'] = 1;  //0 未发货 1已发货 2已收货

                      $data['shipping_time'] = time(); //卖家发货时间

                      $file = $param['file'];
                      if($file){
                        $data['file'] = $file;  
                      }
                      
                      //判断自动确认是否开启
                      if($this->settings['guarantee']['auto_confirm_status'] ==1){
                         // 更新自动确认验收时间
                         $data['auto_confirm_time'] = $this->settings['guarantee']['auto_confirm_day'] *24*3600 + time();
                               
    
                      }
               

                       $msg = '订单已发货成功，等待买家确认';
                       model('guarantee')->editData($data,$where);


               //给买家发送提醒
                    $msg_data['title'] = '卖家发货提醒';
                    $url = url('trade/order',['id'=>$order['id']]);
                    $msg_data['content'] = '交易订单【<a href="'.$url.'">'.$order['title'].'</a>】，卖家 '.$order['seller'].' 已发货，请尽快完成验收工作';
                    $msg_data['to_uid'] = $order['buyer_uid'];
                    $msg_data['create_time'] = time();
                    $msg_data['type'] = 0; //系统通知
                    model('message')->addData($msg_data);
                    return success_json($msg);   
               }
            }
            break; 
            case 4:
            // 买家操作 - 买家已确认，交易成功
            if($order['order_status'] == 1 &&  $order['pay_status'] ==1 && $order['shipping_status'] ==1){
               $where2['uid'] = $order['seller_uid'];
              if($order['buyer_uid'] = session('uid')){
                    model('user')->where($where2)->setInc('money',$order['seller_get']);
                    
                    //添加资金记录
                    $seller = model('user')->infoData($where2);
                    $data2['uid']       = $seller['uid'];
                    $data2['username']  = $seller['username'];
                    $data2['amount']    = $order['seller_get'];
                    $data2['balance']   = $seller['money'];
                    $data2['bankname']  = '站内';
                    $data2['remark']    = '交易成功，订单号：'.$order['id'];
                    $data2['create_time'] = time();
                    model('financeRecord')->addData($data2);

                //给卖家发送通知
                    $msg_data['title'] = '交易完成提醒';
                    $url = url('trade/order',['id'=>$order['id']]);
                    $msg_data['content'] = '交易订单【<a href="'.$url.'">'.$order['title'].'</a>】，买家 '.$order['buyer'].' 已确认！';
                    $msg_data['to_uid'] = $order['seller_uid'];
                    $msg_data['create_time'] = time();
                    $msg_data['type'] = 0; //系统通知
                    model('message')->addData($msg_data);


                    $data['order_status'] = 1; //0 未确认  1  确认  2 取消  
                    $data['pay_status'] = 1;    // 0未付款  1已付款 
                    $data['shipping_status'] = 2;  //0 未发货 1已发货 2 已收货

                    $data['success_time'] = time();  //买家验收成功时间
                    $msg = '订单确认成功，交易完成';
                    model('guarantee')->editData($data,$where);

                      // 更新交易状态为交易成功
                      if(!empty($order['info_id'])){
                        model('guarantee_info')->editData(['status'=>3],['id'=>$order['info_id']]);
                      }

                    return success_json($msg);   
              }
            }
            break;
             case -1:
             if($order['order_status'] <= 1 &&  $order['pay_status'] ==0 && $orde['shipping_status'] ==0){

                if($order['buyer_uid'] = session('uid')  || $order['seller_uid'] = session('uid')){
                // 订单关闭
               
                  $data['order_status']    = 2; //0 未确认  1  确认  2 取消  
                  $data['pay_status']      = 0;    // 0未付款  1已付款 
                  $data['shipping_status'] = 0;  //0 未发货 1已发货 2已收货
                  $msg = '订单已关闭';

    
                   
                   //更新订单状态为关闭
                    model('guarantee')->editData($data,['id'=>$order['id']]);

                   //给卖家发送提醒
                    $msg_data['title'] = '订单关闭提醒';
                    $url = url('trade/order',['id'=>$order['id']]);
                    $msg_data['content'] = '订单已关闭 【<a href="'.$url.'">'.$order['title'].'</a></a>';
                    $msg_data['to_uid'] = $order['seller_uid'];
                    $msg_data['create_time'] = time();
                    $msg_data['type'] = 0; //系统通知
                    model('message')->addData($msg_data);
                 
                  //给买家发送提醒
                    $msg_data2['title'] = '订单关闭提醒';
                    $url = url('trade/order',['id'=>$order['id']]);
                    $msg_data2['content'] = '订单已关闭 【<a href="'.$url.'">'.$order['title'].'</a></a>';
                    $msg_data2['to_uid'] = $order['buyer_uid'];
                    $msg_data2['create_time'] = time();
                    $msg_data2['type'] = 1; //系统通知
                    model('message')->addData($msg_data);
                    return success_json($msg);
                }
             }
            break;
   
          }

  }
// 买卖双方评价
  public function evaluate(){
    
     if($this->request->isAjax()){
       $param = $this->request->param();
       $m['id'] = $param['id'];
       $order = model('guarantee')->infoData($m);

       //判断是卖家还是买家评价的
           if(session('username') == $order['buyer']){
          //买家评价卖家
               $data['buyer_evaluate'] = $param['buyer_evaluate'];
               $data['buyer_evaluate_content'] = !empty($param['buyer_evaluate_content'])?$param['buyer_evaluate_content']:'';
               $data['buyer_works_peed'] = $param['buyer_works_peed'];
               $data['buyer_works_attitude'] = $param['buyer_works_attitude'];
               $data['buyer_works_quality'] = $param['buyer_works_quality'];
               $data['buyer_evaluate_time'] = time();  
               $where2['id']  =$param['id'];
               model('guarantee')->editData($data,$where2);


             $map['uid'] = $order['seller_uid'];
             $userinfo = model('user')->infoData($map);
             $update['buyer_works_peed'] = ($userinfo['buyer_works_peed'] + $param['buyer_works_peed'])/2;
             $update['buyer_works_attitude'] = ($userinfo['buyer_works_attitude'] + $param['buyer_works_attitude'])/2;
             $update['buyer_works_quality'] = ($userinfo['buyer_works_quality'] + $param['buyer_works_quality'])/2;

             $map['uid'] = $order['seller_uid'];
             model('user')->editData($update,$map);
           }elseif(session('username') == $order['seller']){
        // 卖家评价买家
            
             $data['seller_evaluate'] = $param['seller_evaluate'];
             $data['seller_evaluate_content'] = !empty($param['seller_evaluate_content'])?$param['seller_evaluate_content']:'';
             $data['seller_pay']      = $param['seller_pay'];
             $data['seller_attitude'] = $param['seller_attitude'];
             $data['seller_check']    = $param['seller_check']; 
             $data['seller_evaluate_time']    = time(); 


             $where2['id']  =$param['id'];
             model('guarantee')->editData($data,$where2);
           
            //更新卖家评价统计     

             $map['uid'] = $order['buyer_uid'];

             $userinfo = model('user')->infoData($map);
             $update['seller_pay'] = ($userinfo['seller_pay'] + $param['seller_pay'])/2;
             $update['seller_attitude'] = ($userinfo['seller_attitude'] + $param['seller_attitude'])/2;
             $update['seller_check'] = ($userinfo['seller_check'] + $param['seller_check'])/2;

         
               model('user')->editData($update,$map);

           }

 
           return success_json('评价成功！');
      }
   }


 
}